package com.link.base.core.apiutils;

import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.service.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;


/**
 * Copyright  hande Company. All Rights Reserved.
 *  apibasicController ，提供api接口的继承对象
 * @author  yrf
 * @date:    2017/11/7 10:33 AM
 * @version 1.0
 * @Comment  api工程工具类暂时存于bus工程
 */

@Controller
@RequestMapping("/api/base")
public class ApiBasicController<T extends BasicModel> extends BasicController<T> {
    /**
     * @auther yrf
     * @date 2018/11/7 10:40 AM
     * @param source 来源对象
     * @param target 目标对象
     * @return null
     * @throws Exception 报错
     * @comments api中，copy对象用
     */
    public static void apiCopyProperties(Object source, Object target) {
        String[] skipField = {
            "id",
            "usercorpid",
            "createdBy",
            "lastUpdBy",
            "corpid",
            "row_status"
        };
        copyProperties(source, target, null, skipField);
    }

    /**
     * @auther yrf
     * @date 2017/11/7 10:33 AM
     * @param source
     * @param target
     * @param editable
     * @param ignoreProperties
     * @throws BeansException
     * @comments 改写org.springframework.beans.BeanUtils copyProperties 方法逻辑，source -》 target null值忽略
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
            throws BeansException {

        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");

        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                        + "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            boolean flag = (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName())));
            if (flag) {
                PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null
                            && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                            readMethod.getReturnType())) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source);
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            // 修改BeanUtils源码，空值不复制
                            if (value != null) {
                                writeMethod.invoke(target, value);
                            }
                        } catch (Throwable ex) {
                            throw new FatalBeanException(
                                    "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }
    }

    /**
     * @auther yrf
     * @date 2017/11/7 10:50 AM
     * @param entity 实体对象
     * @return null
     * @throws Exception 报错Exception
     * @comments 重写basic controller 的 beforUpsert方法，通过集成Id判断是走新建还是更新
     */
    @Override
    public void beforUpsert(T entity, HttpServletRequest request) throws Exception {
        entity.setLoginCorpId(null);
        if (!StringUtils.isBlank(entity.getIntegrationId())) {
            @SuppressWarnings("unchecked")
            T example = (T) entity.getClass().newInstance();
            example.setIntegrationId(entity.getIntegrationId());
            example.setPageFlag(true);
            example.setPage(1);
            example.setRows(2);
            List<T> list = getBasicService().queryByExamplePage(example);

            if (list == null || list.size() == 0) {
                throw new ServiceException("APIUTILS-001", entity.getIntegrationId());
            } else if (list.size() > 1) {
                throw new ServiceException("APIUTILS-002", entity.getIntegrationId());
            } else {
                T record = list.get(0);
                //entity里字段合并到record，忽略null，此时record为最终需要保存的信息
                apiCopyProperties(entity, record);
                //entity为上级传来的对象，无法修改上级引用，只能把所有字段再复制回entity对象
                BeanUtils.copyProperties(record, entity);
                entity.setRow_status("UPDATE");
            }
        } else {
            entity.setRow_status("NEW");
        }
    }

    /**
     * @auther yrf
     * @date 2017/11/7 10:54 AM
     * @param entity 实体对象
     * @return null
     * @throws Exception 报错Exception
     * @comments 在删除之前，设置usercorpid为空，防止账套伪造
     */
    @Override
    public void beforDelete(T entity, HttpServletRequest request) throws Exception {
        entity.setLoginCorpId(null);
    }
}
